﻿using System;
using BSF.Log;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;

namespace HuntingFishGame.CustomerApiTest
{
    /// <summary>
    /// 模拟请求帮助类
    /// </summary>
    public static class RequestSimulationHelper
    {
        public static void checkResponse(string api, string response)
        {
            CommLog.Write("-------------------------------华丽的分割线----------------------------------");
            CommLog.Write(string.Format("api:{0},result:{1}", api, response));
            bool isSuccess = CheckIsErrorThenThrow(response);
            CommLog.Write("-------------------------------华丽的分割线----------------------------------");
            //断言
            Assert.AreEqual(isSuccess.ToString().ToLower(), "true", true);
        }

        /// <summary>
        /// 检查错误代码，如果有错则抛出微信异常ErrorJsonResultException
        /// </summary>
        /// <param name="returnText"></param>
        public static bool CheckIsErrorThenThrow(string returnText)
        {
            bool isSuccess = false;
            if (returnText.Contains("ret") && returnText.Contains("msg"))
            {
                JsonResult errorResult = JsonConvert.DeserializeObject<JsonResult>(returnText);
                if (errorResult != null)
                {
                    if (errorResult.ret > 0)
                    {
                        isSuccess = true;
                    }
                }
                if (!isSuccess)
                {
                    // 发生错误
                    CommLog.Write(string.Format(String.Format("请求发生错误！错误代码：{0}，错误信息：{1}", (int)errorResult.ret, errorResult.msg)));
                }
                else
                {
                    CommLog.Write("success");
                }
            }
            
            return isSuccess;
        }

    }

    public class JsonResult
    {
        /*
         * {"ret":-1,"msg":"用户名或密码不正确","excuteTime":10.6104}
         * **/
        /// <summary>
        /// 错误码
        /// </summary>
        public int ret { get; set; }
        /// <summary>
        /// 错误信息
        /// </summary>
        public string msg { get; set; }
        /// <summary>
        /// 执行时间
        /// </summary>
        public decimal excuteTime { get; set; }

    }
}
